﻿/*MyPhotoIndex Free Photo Organizer <www.myphotoindex.com>
  Copyright (C) <2006-2009>  <Asaf Yarkoni asaf@yarkoni.net>

  This program is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program.  If not, see <http://www.gnu.org/licenses/>.*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace MyPhotoIndex.Plugins.WebHost
{
    public class Stats
    {
        private const int COUNTER_INTERVAL = 1000;//1 second;

        private Thread m_counterThreadProc;
        private bool m_running = false;

        private int m_requestsPerSecond = 0;

        public int RequestsPerSecond
        {
            get { return m_requestsPerSecond; }
            set { m_requestsPerSecond = value; }
        }

        private List<int> m_requestsPerOneMinute = new List<int>();

        public List<int> RequestsPerOneMinute
        {
            get { return m_requestsPerOneMinute; }
        }

        private int m_requestsPerSecondTemp = 0;


        internal void Start()
        {
            m_running = true;
            m_counterThreadProc = new Thread(new ThreadStart(CountersUpdateThreadProc));
            m_counterThreadProc.Start();
        }

        internal void Stop()
        {
            if (m_counterThreadProc != null)
            {
                m_running = false;
                m_counterThreadProc.Join();
            }
        }

        void CountersUpdateThreadProc()
        {
            while (m_running == true)
            {
                Thread.Sleep(COUNTER_INTERVAL);

                m_requestsPerSecond = m_requestsPerSecondTemp / (COUNTER_INTERVAL / 1000);
                m_requestsPerSecondTemp = 0;

                if (m_requestsPerOneMinute.Count > 60)
                {
                    m_requestsPerOneMinute.RemoveAt(0);
                }

                m_requestsPerOneMinute.Add(m_requestsPerSecond);
            }
        }

        internal void UpdadeRequestCounter(int requestCount)
        {
             m_requestsPerSecondTemp++;
        }
    }
}
